package com.summer.ASM;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;

public class MyClassLoader extends ClassLoader {

	@SuppressWarnings("deprecation")
	public Class<?> defineMyClass(byte[] b, int off, int len) {
		return super.defineClass(b, off, len);
	}

	public Class<?> defineMyClass(String name, byte[] b, int off, int len) {
		return super.defineClass(name, b, off, len);
	}

	public static void main(String[] args) throws IOException {
		// 读取本地的class文件内的字节码，转换成字节码数组
		File file = new File(".");
		@SuppressWarnings("resource")
//		InputStream input = new FileInputStream(file.getCanonicalPath() + "\\bin\\com\\summer\\ASM\\Programmer.class");
//		InputStream input = new FileInputStream("D://Programmer.class");
//		InputStream input = new FileInputStream("D://temp//com//samples//Programmer.class");
		InputStream input = new FileInputStream("C://summer//com//samples//Programmer.class");
		byte[] result = new byte[1024];

		int count = input.read(result);
		// 使用自定义的类加载器将 byte字节码数组转换为对应的class对象
		MyClassLoader loader = new MyClassLoader();
		Class<?> clazz = loader.defineMyClass(result, 0, count);
//		Class<?> clazz = loader.defineMyClass(null,result, 0, count);
		// 测试加载是否成功，打印class 对象的名称
		System.out.println(clazz.getCanonicalName());

		try {
			// 实例化一个Programmer对象
			Object obj = clazz.newInstance();

			// 调用Programmer的code方法
			clazz.getMethod("code", (Class<?>[])null).invoke(obj, new Object[0]);
//			Method method= clazz.getMethod("code",(Class<?>[])null);
//			method.invoke(obj, new Object[0]);
		} catch (IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException | SecurityException ex) {
			ex.printStackTrace();
		}
	}
}
